var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var _Cart= require("../../modules/cart_module.js");
let setTimerId = null;
var app = getApp();
Page({
  data: {
    goodsList:[],
    cartGoods: [], // 有效商品
    invalidCartGoods: [], //失效商品
    cartTotal: 0, // 选中 的总价
    checkboxArray: [], //存放选中的索引数组
    isCheckedAll: false,
    slideButtons: [{
      type: 'warn',
      text: '删除',
    }],
    remainingSecondsArr: [], //有活动的剩余时间
    activityNum: 0, // 有活动的商品数量
    savingAmount: 0,
    orderGoods: [] //选中下单的商品
  },
  onLoad: function (options) {
    this.getRecommendGoodList();
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function () {
    // 页面渲染完成
  },
  onPullDownRefresh: function () {
    this.onShow();
  },
  onShow: function () {
    app.globalData.isCartPage = true;
    this.getCartList();
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');
    if (userInfo && token) {
        app.globalData.userInfo = userInfo;
        app.globalData.token = token;
    }
    // if(app.globalData.cartNum > 0){
      wx.removeTabBarBadge({index:3})
    // }
    wx.stopPullDownRefresh()

  },
  onHide: function () {
    // 页面隐藏
    console.log("页面隐藏")
    app.globalData.isCartPage = false;
    clearInterval(intervalNum);
  },
  onUnload: function () {
    // 页面关闭
    console.log("页面关闭");
    clearTimeout(setTimerId)
    app.globalData.isCartPage = false;
  },
  gotoIndex: function(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  getRecommendGoodList(){
    this.findGoodsRequest({
      isRecommend: true
    }).then(res=>{
      console.log(1223,res.result)
      if(res.result.length > 0){
        this.setData({
          goodsList:res.result,
        })
        console.log(222,this.data.goodsList)
      }
    }).catch(err=>{
      console.log(err.message)
    })
  },
  findGoodsRequest(data = {}){
    wx.showLoading({
      title: "正在加载"
    })

    let url = api.indexUrl.getGoodList+'?current=1&size=21';

    return new Promise((resolve, rejected)=>{
      util.request(url, data, "POST").then((res)=>{
        resolve(res);
        wx.hideLoading();
      }).catch(err=>{
        rejected(err);
        wx.hideLoading();
      })
    })
  },
  // 获取购物车
  getCartList: function () {
    let that = this;
    wx.showLoading({
      title: "",
    })
    util.request(api.cartUrl.cartList).then((res) =>{
      const data = res.result || {},
            list = data.validCartCommodityList || [],
            invalidCartGoods = data.invalidCartCommodityList || [],
            remainingSecondsArr = [],
            checkboxArray = [];
      let activityNum = 0;
      if(list && (list.length + invalidCartGoods.length) > 0){
        list.length && list.forEach((item, index)=> {
          item.checked = true;
          if(item.remainingSeconds > 0){
            activityNum++;
          }
          checkboxArray.push(index);
          remainingSecondsArr[index] = item.remainingSeconds
        });
        this.setData({
          cartTotal: data.totalAmount,
          cartGoods: list,
          invalidCartGoods,
          remainingSecondsArr,
          activityNum,
          savingAmount: data.savingAmount,
          isCheckedAll: true,
          checkboxArray,
          orderGoods: list
        })
        // this.totalPrice();
        // 有活动商品且时间差不为0
        if(activityNum > 0){
          this.minusRemainingSeconeds();
        }
      }

      wx.stopPullDownRefresh();
    }).finally(()=>{
      wx.hideLoading();
    })
  },
  checkedItem: function (event) {
    let { itemIndex } = event.target.dataset;
    let that = this;

    if (!this.data.isEditCart) {
      util.request(api.CartChecked, { productIds: that.data.cartGoods[itemIndex].product_id, isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1 }, 'POST').then(function (res) {
        if (res.errno === 0) {
          console.log(res.data);
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
        if (index == itemIndex){
          element.checked = !element.checked;
        }

        return element;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  // 滑动删除按钮事件
  delItem:function(e){
    // 获取删除项的下标
    let { itemIndex, id } = e.currentTarget.dataset;
    this.updateCart(id, 0 , itemIndex, "delete");

  },
  // 多选事件
  checkboxChange:function(e){
    const choose = e.detail.value;
    this.setData({
      checkboxArray: choose,
      isCheckedAll: choose.length === this.data.cartGoods.length ? true: false
    })
    this.totalPrice();
  },
  // 计算总价
  totalPrice:function(){
    let totalPrice = 0,
        savingAmount = 0;
    const list = this.data.cartGoods,
          choose = this.data.checkboxArray,
          orderGoods = [];
    choose.length && choose.map((index)=>{
      const { quantity, sellingPrice, savingPrice } = list[index];
      totalPrice += quantity * sellingPrice;
      savingAmount += quantity * savingPrice;
      orderGoods.push(list[index]);
    })
    this.setData({
      cartTotal: totalPrice.toFixed(2),
      savingAmount:savingAmount.toFixed(2),
      orderGoods
    })
  },
  getCheckedGoodsCount: function(){
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function (v) {
      if (v.checked === true) {
        checkedGoodsCount += v.number;
      }
    });
    console.log(checkedGoodsCount);
    return checkedGoodsCount;
  },
  // 点击全选与非全选
  checkedAll: function (e) {
    const flag = e.detail.value.length;
    const list = this.data.cartGoods;
    const newChooseArr = []
    if(flag && list.length){
      // 全选
      list.forEach((item, index)=>{
        newChooseArr.push(index);
        item.checked = true;
      })
    }else{
      list.forEach(item => item.checked = false)
    }
    this.setData({
      checkboxArray: newChooseArr,
      cartGoods: list
    })
    this.totalPrice();

  },
  editCart: function () {
    var that = this;
    if (this.data.isEditCart) {
      this.getCartList();
      this.setData({
        isEditCart: !this.data.isEditCart
      });
    } else {
      //编辑状态
      let tmpCartList = this.data.cartGoods.map(function (v) {
        v.checked = false;
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },
  // 更新购物车数量
  updateCart: async function (id, update, index, flag="") {
    console.log("enter updateCart update is ",update);
    const list = this.data.cartGoods;
    // 请求
    const res = await _Cart._cartUpdate({
      id: id,
      update: update,
      list,
      changeProperty: "quantity"
    });
    // 本地更新购物车数量
    if(res.id){
      if(flag){
        // 删除
        let activityNum = 0,
            remainingSecondsArr = [];
        list.splice(index, 1);
        list.forEach((item, index)=>{
          if(item.remainingSeconds > 0){
            activityNum++;
          }
          remainingSecondsArr[index] = item.remainingSeconds
        })
        this.setData({

          cartGoods: list,
          remainingSecondsArr,
          activityNum
        })
      }else{
        const item_str = 'cartGoods[' + res.index + '].quantity'
        this.setData({
          [item_str]: res.num
        })
      }
      this.totalPrice();
    }
  },
  // 购物车减1
  cutNumber: function (event) {
    console.log("enter cutNumber event is ",event);
    const { itemIndex, id } = event.target.dataset;
    // let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    if(cartItem.quantity <= 1){
      return wx.showToast({
        title: "左滑删除商品",
        icon: "none"
      })
    }

    this.updateCart(id, -1, itemIndex);
  },
  // 购物车加1
  addNumber: function (event) {
    console.log("enter addNumber event is ",event);
    const { itemIndex, id } = event.target.dataset;
    this.updateCart(id, 1, itemIndex);
  },
  goLogin() {

      wx.navigateTo({
          url: '/pages/authorized/index'
      })
  },
  checkoutOrder: function () {
    if(!app.globalData.userInfo || !app.globalData.userInfo.phone){
      this.goLogin();
      return ;
    }

    wx.setStorageSync("orderGoodsList", this.data.orderGoods);
    wx.navigateTo({
      url: "/pages/orderPay/orderPay?activityType=3",
    })
  },
  deleteCart: function () {
    //获取已选择的商品
    let that = this;

    let productIds = this.data.cartGoods.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (productIds.length <= 0) {
      return false;
    }

    productIds = productIds.map(function (element, index, array) {
      if (element.checked == true) {
        return element.product_id;
      }
    });


    util.request(api.CartDelete, {
      productIds: productIds.join(',')
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        console.log(res.data);
        let cartList = res.data.cartList.map(v => {
          console.log(v);
          v.checked = false;
          return v;
        });

        that.setData({
          cartGoods: cartList,
          cartTotal: res.data.cartTotal
        });
      }

      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  // 活动商品倒计时
  minusRemainingSeconeds:function(){
    let activityNum = 0
    const arr = this.data.remainingSecondsArr;
    arr.forEach((item, index, array) => {
      if(item === 0){
        return;
      }
      activityNum++;
      array[index] =  item - 1
    })
    this.setData({
      remainingSecondsArr: arr,
      activityNum
    })
    if(activityNum > 0){
      setTimerId = setTimeout(()=>{
        this.minusRemainingSeconeds();
      }, 1000);
    }
  },
  cartRemove: function(){
    wx.showLoading({
      title: "正在清空"
    });
    util.request(api.cartUrl.cartRemove, {}, 'PUT').then(async (res)=>{
      await this.getMemberInfo();
      wx.hideLoading();
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      this.onShow();
    });
  },
  getMemberInfo() {
    let _this = this;
    return new Promise((resolve,rejected)=>{
        util.request(api.MemberInfo).then(res=>{
            _this.setData({
                userInfo:res.result
            })
            app.globalData.userInfo = res.result;
            app.globalData.cartNum = res.result.shoppingCartCount
            resolve();
        }).catch(err=>{
            console.log(err)
            rejected();
        })
    })
},
})
